//
//  CalculateViewController.m
//  PregnancyAPP
//
//  Created by APPYING on 14-2-11.
//  Copyright (c) 2014年 APPYING. All rights reserved.
//

#import "CalculateViewController.h"
#import "PicBigViewController.h"
#import "MainPageViewController.h"
#import "MobClick.h"
#import "FootViewController.h"
#import "ShowAdvertisement.h"
#import "TimeViewController.h"

@interface CalculateViewController ()

@end

@implementation CalculateViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    self.navigationController.navigationBar.alpha = 1.0;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    TimeViewController *time = [[TimeViewController alloc] init];
    NSDictionary *dic = [time getYearMonthDayHourMinuteSecondFromCurrent];
    NSString *year = [self returnJiaLingString:[[dic objectForKey:@"year"] intValue]];
    NSString *month = [self returnJiaLingString:[[dic objectForKey:@"month"] intValue]];
    NSString *day = [self returnJiaLingString:[[dic objectForKey:@"day"] intValue]];
    titleLab.text = [NSString stringWithFormat:@"%@-%@-%@", year, month, day];
    
    /*
    if (_month < 10) {
        titleLab.text = [NSString stringWithFormat:@"%d-0%d-%d", (int)_year, (int)_month, (int)_day];
    }
    if (_day < 10) {
        titleLab.text = [NSString stringWithFormat:@"%d-%d-0%d", (int)_year, (int)_month, (int)_day];
    }
    if (_day < 10 && _month < 10) {
        titleLab.text = [NSString stringWithFormat:@"%d-0%d-0%d", (int)_year, (int)_month, (int)_day];
    }
    if (_day >= 10 && _month >= 10) {
        titleLab.text = [NSString stringWithFormat:@"%d-%d-%d", (int)_year, (int)_month, (int)_day];
    }
     */
    
    self.navigationController.navigationBar.barTintColor = HexRGB(0xffcbd8);
    
}

- (NSString *)returnJiaLingString:(int)sender {
    if (sender < 10) {
        return [NSString stringWithFormat:@"0%d", sender];
    } else {
        return [NSString stringWithFormat:@"%d", sender];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = NO;
    self.view.backgroundColor = [UIColor whiteColor];
//    self.edgesForExtendedLayout= UIRectEdgeTop;
    
    //UMeng
//    NSDateFormatter *dateFor = [[NSDateFormatter alloc] init];
//    [dateFor setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
//    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
//                          [dateFor stringFromDate:self.pregnancyData], @"lastTime", nil];
//    [MobClick event:@"TheLast" attributes:dict];

//    version = [[UIDevice currentDevice].systemVersion doubleValue];

    //将数据记录到本地
    NSFileManager *fm = [NSFileManager defaultManager];
    //找到Documents文件所在的路径
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //取得第一个Documents文件夹的路径
    NSString *filePath = [path objectAtIndex:0];
    //把TestPlist文件加入
    NSString *plistPath = [filePath stringByAppendingPathComponent:@"test.plist"];
    //开始创建文件
    [fm createFileAtPath:plistPath contents:nil attributes:nil];
    //创建一个字典
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",(long)self.day],@"day",[NSString stringWithFormat:@"%ld",(long)self.month],@"month",[NSString stringWithFormat:@"%ld",(long)self.year],@"year", nil];
    //把数据写入plist文件
    [dic writeToFile:plistPath atomically:YES];
    
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"< 设置"style:UIBarButtonItemStyleBordered target:self action:@selector(popToPreviousView)];
    //设置返回按钮的字体显示
//    NSDictionary *font1=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,[UIFont fontWithName:@"YuppySC-Regular" size:20],UITextAttributeFont, nil];
//    NSDictionary *font1=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor],UITextAttributeTextColor,[UIFont systemFontOfSize:20],UITextAttributeFont, nil];
//    [[UIBarButtonItem appearance] setTitleTextAttributes:font1 forState:UIControlStateNormal];
    
    UIButton *backButton = [[UIButton alloc] init];
    backButton.frame = CGRectMake(0, 0, 47, 44);
    [backButton addTarget:self action:@selector(popToPreviousView) forControlEvents:UIControlEventTouchUpInside];
    [backButton setBackgroundImage:[UIImage imageNamed:@"backSeting"] forState:UIControlStateNormal];
    [backButton setBackgroundImage:[UIImage imageNamed:@"backSeting"] forState:UIControlStateHighlighted];
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem =leftItem;
    
    UIView *blaceView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 47, 44)];
    blaceView.backgroundColor = [UIColor clearColor];
    
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:blaceView];
    self.navigationItem.rightBarButtonItem = right;
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Kwidth - 88 - 44, 44)];
    titleView.backgroundColor = [UIColor clearColor];
    titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, Kwidth - 88 - 44, 15)];
    titleLab.backgroundColor = [UIColor clearColor];
    titleLab.font = [UIFont boldSystemFontOfSize:18];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.textColor = HexRGB(0xed4f78);
    [titleView addSubview:titleLab];
    
    UILabel *titleWord = [[UILabel alloc] initWithFrame:CGRectMake(146, 22, Kwidth - 88 - 44, 12)];
    titleWord.text = @"今天";
    titleWord.backgroundColor = [UIColor clearColor];
    titleWord.font = [UIFont boldSystemFontOfSize:12];
    titleWord.textAlignment = NSTextAlignmentLeft;
    titleWord.textColor = HexRGB(0xed4f78);
    [titleView addSubview:titleWord];

    
    self.navigationItem.titleView = titleView;
    self.navigationItem.titleView.frame = CGRectMake(0, 0, Kwidth, 44);
    
    
    //获取当前时间显示在title上
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
//    self.title = [NSString stringWithFormat:@"今天%@", currentDateStr];
//    
//    //自定义字体
//    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,[UIFont fontWithName:@"YuppySC-Regular" size:20],UITextAttributeFont, nil];
//    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    
    //怀孕日期计算
    NSTimeInterval secondsInterval= [[NSDate date] timeIntervalSinceDate:self.pregnancyData];
    pregnancyDay = secondsInterval/(60*60*24);

    
    //滚动条UIScrollView
    sclMain = [[UIScrollView alloc] init];
    sclMain.frame = CGRectMake(0, 64, Kwidth, Kheight - 64);
    sclMain.backgroundColor = [UIColor clearColor];
    sclMain.delegate = self;
    sclMain.showsVerticalScrollIndicator = NO;
    [self.view addSubview:sclMain];
//    if (HEIGHT < 500)//IOS 7.0 以上
//    {
        sclMain.contentSize = CGSizeMake(Kwidth, 441);
//    }
    
    // 文字显示粉红背景
    UIView *finkBg = [[UIView alloc] init];
    finkBg.backgroundColor = HexRGB(0xbe2746);
    finkBg.frame = CGRectMake(0, -64, Kwidth, 207);
    [sclMain addSubview:finkBg];
    
    NSString *str;
    UILabel *labWord;
    CGSize wordSize;
    
    for (int i = 0; i < 11; i++) {
        labWord = [[UILabel alloc] init];
        labWord.textColor = HexRGB(0xf3acbe);
        if(i == 0) {
            str = @"您已怀孕";
            wordSize = [self contentCellHeightWithText:str andFont:[UIFont systemFontOfSize:17]];
            labWord.frame = CGRectMake(30, 26, wordSize.width, wordSize.height);
            labWord.font = [UIFont systemFontOfSize:17];
        }
        if(i == 1) {
            str = @"第";
            wordSize = [self contentCellHeightWithText:str andFont:[UIFont systemFontOfSize:20]];
            labWord.frame = CGRectMake(30, 76, wordSize.width, wordSize.height);
            labWord.font = [UIFont systemFontOfSize:20];
        }
        if(i == 2) {
            str = [NSString stringWithFormat:@"%d", (pregnancyDay - 1)/7 + 1];
            if ([str isEqualToString:@"41"]) {
                str = @"40";
            }
            wordSize = [self contentCellHeightWithText:str andFont:[UIFont systemFontOfSize:45]];
            if(pregnancyDay/7 >= 10) {
                labWord.frame = CGRectMake(58, 54, wordSize.width, wordSize.height);
            } else {
                labWord.frame = CGRectMake(71, 54, wordSize.width, wordSize.height);
            }
            labWord.font = [UIFont systemFontOfSize:45];
            labWord.textColor = HexRGB(0xfff602);
        }if(i == 3) {
            str = @"周        第";
            wordSize = [self contentCellHeightWithText:str andFont:[UIFont systemFontOfSize:20]];
            labWord.frame = CGRectMake(114, 76, wordSize.width, wordSize.height);
            labWord.font = [UIFont systemFontOfSize:20];
        }if(i == 4) {
            str = [NSString stringWithFormat:@"%d", pregnancyDay - 7 * ((pregnancyDay - 1) / 7)];
            
//            if ((pregnancyDay/7 + 1) == 41 && ) {
//                str = @"7";
//            }
            wordSize = [self contentCellHeightWithText:str andFont:[UIFont systemFontOfSize:45]];
            labWord.frame = CGRectMake(214, 54, wordSize.width, wordSize.height);
            labWord.font = [UIFont systemFontOfSize:45];
            labWord.textColor = HexRGB(0xfff602);
        }
        if(i == 5) {
            str = @"天";
            wordSize = [self contentCellHeightWithText:str andFont:[UIFont systemFontOfSize:20]];
            labWord.frame = CGRectMake(251, 76, wordSize.width, wordSize.height);
            labWord.font = [UIFont systemFontOfSize:20];
        }
        
        if(i == 6) {
            str = @"离预产期还有";
            wordSize = [self contentCellHeightWithText:str andFont:[UIFont systemFontOfSize:18]];
            labWord.frame = CGRectMake(30, 122, wordSize.width, wordSize.height);
            labWord.font = [UIFont systemFontOfSize:18];
        }
        if(i == 7) {
            str = [NSString stringWithFormat:@"%d", 280-pregnancyDay];
            wordSize = [self contentCellHeightWithText:str andFont:[UIFont systemFontOfSize:35]];
            if((280-pregnancyDay) < 10) {
                labWord.frame = CGRectMake(144, 107, wordSize.width, wordSize.height);
            } else if ((280-pregnancyDay) >= 10 && (280-pregnancyDay) < 100) {
                labWord.frame = CGRectMake(144, 107, wordSize.width, wordSize.height);
            } else {
                labWord.frame = CGRectMake(144, 107, wordSize.width, wordSize.height);
            }
            labWord.font = [UIFont systemFontOfSize:35];
            labWord.textColor = [UIColor whiteColor];
        }
        if(i == 8) {
            str = @"天";
            wordSize = [self contentCellHeightWithText:str andFont:[UIFont systemFontOfSize:18]];
            
            if((280-pregnancyDay) < 10) {
                labWord.frame = CGRectMake(166, 122, wordSize.width, wordSize.height);
            } else if ((280-pregnancyDay) >= 10 && (280-pregnancyDay) < 100) {
                labWord.frame = CGRectMake(186, 122, wordSize.width, wordSize.height);
            } else {
                labWord.frame = CGRectMake(206, 122, wordSize.width, wordSize.height);
            }
            
            labWord.font = [UIFont systemFontOfSize:18];
        }
        if(i == 9) {
            str = @"预产期  ";
            wordSize = [self contentCellHeightWithText:str andFont:[UIFont systemFontOfSize:18]];
            labWord.frame = CGRectMake(30, 163, wordSize.width, wordSize.height);
            labWord.font = [UIFont systemFontOfSize:18];
        }
        if(i == 10) {
            NSTimeInterval time = (280-pregnancyDay) * 24 * 60 * 60;//单位为秒
            NSDate *date = [self.pregnancyData initWithTimeIntervalSinceNow:+time];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            str = [dateFormatter stringFromDate:date];

            wordSize = [self contentCellHeightWithText:str andFont:[UIFont systemFontOfSize:18]];
            labWord.frame = CGRectMake(97, 163, wordSize.width, wordSize.height);
            labWord.font = [UIFont systemFontOfSize:18];
            labWord.textColor = [UIColor whiteColor];
        }
        labWord.text = str;
        [finkBg addSubview:labWord];
        labWord = nil;
    }
    
    // 按钮，点击进入食物页面
    UIButton *footButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 143, Kwidth, 40)];
    [footButton setBackgroundImage:[UIImage imageNamed:@"selectIntoFood"] forState:UIControlStateNormal];
    [footButton setBackgroundImage:[UIImage imageNamed:@"selectIntoFood"] forState:UIControlStateHighlighted];
    [footButton addTarget:self action:@selector(intoFootPage:) forControlEvents:UIControlEventTouchUpInside];
    [sclMain addSubview:footButton];
    
    //定义一个白色的背景，然后将图片贴在背景上面显示，这样会让图片看起来更好看
    UIView *whitePicBgView = [[UIView alloc] init];
    whitePicBgView.backgroundColor = [UIColor whiteColor];
    whitePicBgView.frame = CGRectMake(0, 183, Kwidth, 239);

    [sclMain addSubview:whitePicBgView];
    
    UIImageView *imgView = [[UIImageView alloc]init];

    NSString *strPic;
    if (((int)pregnancyDay - 1)/7 < 10) {
        if(((int)pregnancyDay - 1)/7 == 0) {
            strPic = @"01";
        } else {
            strPic = [NSString stringWithFormat:@"0%d", ((int)pregnancyDay - 1)/7 + 1];
        }
    } else {
        strPic = [NSString stringWithFormat:@"%d", ((int)pregnancyDay - 1)/7 + 1];
    }
    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",strPic]];
    xuanzhuanImage = [self image:image rotation:image.imageOrientation];
    imgView.image = image;
    imgView.frame = CGRectMake(0, 5, Kwidth, 224);
    [whitePicBgView addSubview:imgView];
    
    //在图片之上添加一个有点击事件的按钮
    UIButton *btPic = [[UIButton alloc] initWithFrame:CGRectMake(imgView.frame.origin.x, imgView.frame.origin.y, imgView.frame.size.width, imgView.frame.size.height)];
    [btPic addTarget:self action:@selector(clickPic:) forControlEvents:UIControlEventTouchUpInside];
    [whitePicBgView addSubview:btPic];
    
    // 添加广告SDK
    ShowAdvertisement *test = [[ShowAdvertisement alloc] init];
    test.target = test;
    UIView *adView = [test showAdvertisement:@"5412ba8de4b080380a486a57"];
    [self.navigationController.view addSubview:adView];

}

//返回上一个页面
- (void)popToPreviousView {
    if(_delegate != nil && [self.delegate respondsToSelector:@selector(DoSomething)]) {
        [self.delegate DoSomething];
        [self.navigationController popViewControllerAnimated:NO];
    }
}

// 进入饮食页面
- (void)intoFootPage: (UIButton *)sender {
    FootViewController *footViewController = [[FootViewController alloc] init];
    footViewController.pregnancyDay = pregnancyDay;
    [self.navigationController pushViewController:footViewController animated:YES];
}

- (void)clickPic:(UIButton *)button {
    
    if (bigImage == nil) {
        bigImage = [[UIImageView alloc] initWithImage:xuanzhuanImage];
        bigImage.frame = CGRectMake(0, 0, Kwidth, Kheight);
        bigImage.userInteractionEnabled = YES;
    }
    [self.navigationController.view addSubview:bigImage];
    
    UIButton *bigImageRemove = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, Kwidth, Kheight)];
    [bigImageRemove addTarget:self action:@selector(removeBigPic:) forControlEvents:UIControlEventTouchUpInside];
    [bigImage addSubview:bigImageRemove];
}

- (void)removeBigPic:(UIButton *)sender {
    [bigImage removeFromSuperview];
}

//判断字体大小
- (CGSize)contentCellHeightWithText:(NSString*)text andFont:(UIFont *)font {
    //设置字体
    CGSize size = CGSizeMake(300, 20000.0f);//注：这个宽：300 是你要显示的宽度既固定的宽度，高度可以依照自己的需求而定
    if (version > 6)//IOS 7.0 以上
    {
        NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
        size =[text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:tdic context:nil].size;
    }
    else
    {
        size = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];//ios7以上已经摒弃的这个方法
    }
    return size;
}

// 旋转图片
/**
 *  图片宽度大于高度 旋转90°
 *
 *  @param aImage UIImage
 *
 *  @return UIImage
 */

- (UIImage *)image:(UIImage *)image rotation:(UIImageOrientation)orientation
{
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    
    if (image.size.width > image.size.height) {
        rotate = M_PI_2;
        rect = CGRectMake(0, 0, image.size.height, image.size.width);
        translateX = 0;
        translateY = -rect.size.width;
        scaleY = rect.size.width/rect.size.height;
        scaleX = rect.size.height/rect.size.width;
    }
    else{
        rotate = 0.0;
        rect = CGRectMake(0, 0, image.size.width, image.size.height);
        translateX = 0;
        translateY = 0;
    }
    //    switch (orientation) {
    //        case UIImageOrientationLeft:
    //            rotate = M_PI_2;
    //            rect = CGRectMake(0, 0, image.size.height, image.size.width);
    //            translateX = 0;
    //            translateY = -rect.size.width;
    //            scaleY = rect.size.width/rect.size.height;
    //            scaleX = rect.size.height/rect.size.width;
    //            break;
    //        case UIImageOrientationRight:
    //            rotate = 3 * M_PI_2;
    //            rect = CGRectMake(0, 0, image.size.height, image.size.width);
    //            translateX = -rect.size.height;
    //            translateY = 0;
    //            scaleY = rect.size.width/rect.size.height;
    //            scaleX = rect.size.height/rect.size.width;
    //            break;
    //        case UIImageOrientationDown:
    //            rotate = M_PI;
    //            rect = CGRectMake(0, 0, image.size.width, image.size.height);
    //            translateX = -rect.size.width;
    //            translateY = -rect.size.height;
    //            break;
    //        default:
    //
    //            break;
    //    }
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    
    return newPic;
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
